package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.IncomeBill;
import com.zhentao.service.IncomeBillService;
import com.zhentao.util.ExcelExportUtil;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 收入单管理控制器
 */
@RestController
@RequestMapping("/finance/incomeBill")
public class IncomeBillController {

    @Autowired
    private IncomeBillService incomeBillService;

    /**
     * 分页查询收入单
     */
    @GetMapping("/list")
    public Result<Page<IncomeBill>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long itemId,
            @RequestParam(required = false) String billNo,
            @RequestParam(required = false) Long tenantId) {
        
        try {
            Page<IncomeBill> page = new Page<>(current, size);
            QueryWrapper<IncomeBill> wrapper = new QueryWrapper<>();
            
            if (status != null) {
                wrapper.eq("status", status);
            }
            if (itemId != null) {
                wrapper.eq("item_id", itemId);
            }
            if (StringUtils.hasText(billNo)) {
                wrapper.like("bill_no", billNo);
            }
            if (tenantId != null) {
                wrapper.eq("tenant_id", tenantId);
            }
            wrapper.orderByDesc("create_time");
            
            IPage<IncomeBill> result = incomeBillService.page(page, wrapper);
            return Result.success((Page<IncomeBill>) result);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询收入单
     */
    @GetMapping("/{id}")
    public Result<IncomeBill> getById(@PathVariable Long id) {
        try {
            IncomeBill incomeBill = incomeBillService.getById(id);
            if (incomeBill != null) {
                return Result.success(incomeBill);
            } else {
                return Result.error("收入单不存在");
            }
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增收入单
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody IncomeBill incomeBill) {
        try {
            boolean success = incomeBillService.save(incomeBill);
            if (success) {
                return Result.success("新增成功");
            } else {
                return Result.error("新增失败");
            }
        } catch (Exception e) {
            return Result.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改收入单
     */
    @PutMapping("/update")
    public Result<String> update(@RequestBody IncomeBill incomeBill) {
        try {
            boolean success = incomeBillService.updateById(incomeBill);
            if (success) {
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            return Result.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除收入单
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            boolean success = incomeBillService.removeById(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 审核收入单
     */
    @PostMapping("/approve/{id}")
    public Result<String> approve(@PathVariable Long id) {
        try {
            IncomeBill incomeBill = incomeBillService.getById(id);
            if (incomeBill == null) {
                return Result.error("收入单不存在");
            }
            
            incomeBill.setStatus(1); // 设置为已审核
            boolean success = incomeBillService.updateById(incomeBill);
            if (success) {
                return Result.success("审核成功");
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            return Result.error("审核失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除收入单
     */
    @PostMapping("/batchDelete")
    public Result<String> batchDelete(@RequestBody List<Long> ids) {
        try {
            boolean success = incomeBillService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量审核收入单
     */
    @PostMapping("/batchApprove")
    public Result<String> batchApprove(@RequestBody List<Long> ids) {
        try {
            List<IncomeBill> incomeBills = new ArrayList<>();
            for (Long id : ids) {
                IncomeBill incomeBill = new IncomeBill();
                incomeBill.setId(id);
                incomeBill.setStatus(1); // 设置为已审核
                incomeBills.add(incomeBill);
            }
            
            boolean success = incomeBillService.updateBatchById(incomeBills);
            if (success) {
                return Result.success("批量审核成功");
            } else {
                return Result.error("批量审核失败");
            }
        } catch (Exception e) {
            return Result.error("批量审核失败：" + e.getMessage());
        }
    }

    /**
     * 获取统计数据
     */
    @GetMapping("/stats")
    public Result<Object> getStats() {
        try {
            QueryWrapper<IncomeBill> wrapper = new QueryWrapper<>();
            wrapper.eq("status", 1); // 已审核的收入单
            
            List<IncomeBill> incomeBills = incomeBillService.list(wrapper);
            
            BigDecimal totalAmount = BigDecimal.ZERO;
            BigDecimal monthlyAmount = BigDecimal.ZERO;
            int approvedCount = incomeBills.size();
            int pendingCount = 0;
            
            // 计算总金额和本月金额
            for (IncomeBill bill : incomeBills) {
                if (bill.getAmount() != null) {
                    totalAmount = totalAmount.add(bill.getAmount());
                    
                    // 检查是否是本月的数据（简化处理）
                    if (bill.getBillDate() != null) {
                        // 将java.util.Date转换为java.time.LocalDate
                        java.time.Instant instant = bill.getBillDate().toInstant();
                        java.time.ZoneId zoneId = java.time.ZoneId.systemDefault();
                        java.time.LocalDate billDate = instant.atZone(zoneId).toLocalDate();
                        
                        java.time.LocalDate now = java.time.LocalDate.now();
                        if (billDate.getYear() == now.getYear() && billDate.getMonth() == now.getMonth()) {
                            monthlyAmount = monthlyAmount.add(bill.getAmount());
                        }
                    }
                }
            }
            
            // 获取待审核数量
            QueryWrapper<IncomeBill> pendingWrapper = new QueryWrapper<>();
            pendingWrapper.eq("status", 0);
            pendingCount = (int) incomeBillService.count(pendingWrapper);
            
            java.util.Map<String, Object> stats = new java.util.HashMap<>();
            stats.put("totalAmount", totalAmount);
            stats.put("monthlyAmount", monthlyAmount);
            stats.put("approvedCount", approvedCount);
            stats.put("pendingCount", pendingCount);
            
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 导出收入单数据
     */
    @GetMapping("/export")
    public void export(IncomeBill query, HttpServletResponse response) throws IOException {
        try {
            QueryWrapper<IncomeBill> wrapper = new QueryWrapper<>();
            
            if (query != null) {
                if (query.getStatus() != null) {
                    wrapper.eq("status", query.getStatus());
                }
                if (query.getItemId() != null) {
                    wrapper.eq("item_id", query.getItemId());
                }
                if (StringUtils.hasText(query.getBillNo())) {
                    wrapper.like("bill_no", query.getBillNo());
                }
                if (query.getTenantId() != null) {
                    wrapper.eq("tenant_id", query.getTenantId());
                }
            }
            wrapper.orderByDesc("create_time");
            
            // 查询所有数据
            List<IncomeBill> incomeBills = incomeBillService.list(wrapper);
            
            // 准备Excel数据
            List<String> headers = new ArrayList<>();
            headers.add("单据编号");
            headers.add("收入项目");
            headers.add("金额");
            headers.add("单据日期");
            headers.add("状态");
            headers.add("备注");
            headers.add("创建时间");
            
            List<List<Object>> dataList = new ArrayList<>();
            for (IncomeBill bill : incomeBills) {
                List<Object> row = new ArrayList<>();
                row.add(bill.getBillNo() != null ? bill.getBillNo() : "");
                row.add(bill.getItemId() != null ? bill.getItemId().toString() : "");
                row.add(bill.getAmount() != null ? bill.getAmount().toString() : "0.00");
                row.add(bill.getBillDate() != null ? bill.getBillDate().toString() : "");
                row.add(getStatusText(bill.getStatus()));
                row.add(bill.getRemark() != null ? bill.getRemark() : "");
                row.add(bill.getCreateTime() != null ? bill.getCreateTime().toString() : "");
                dataList.add(row);
            }
            
            // 导出Excel
            String fileName = "收入管理数据_" + java.time.LocalDate.now();
            ExcelExportUtil.exportToResponse(response, fileName, headers, dataList);
            
        } catch (Exception e) {
            // 如果导出失败，返回错误信息
            response.reset();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("导出失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "待审核";
            case 1: return "已审核";
            case 2: return "已拒绝";
            default: return "未知";
        }
    }
}
